package sm.upgrade.api.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.orm.hibernate3.HibernateTemplate;

import sm.upgrade.api.DataUpgradeInterceptor;
import sm.upgrade.api.UpgradePhase;
import sm.upgrade.util.UpgradeResult;
import sm.upgrade.util.UpgradeUtil;
import sm.util.SMMap;

public class DefaultDataUpgradeInterceptor implements DataUpgradeInterceptor {

	protected List<SMMap> upgradeResults = new ArrayList<SMMap>();

	protected List<SMMap> oldDatas = new ArrayList<SMMap>();

	protected List<SMMap> newDatas = new ArrayList<SMMap>();

	protected HibernateTemplate template;

	public void setTemplate(HibernateTemplate template) {
		this.template = template;
	}

	@Override
	public void beforeSave(String entityName, SMMap data) {
		// do nothing
	}

	@Override
	public void addData(String entityName, SMMap upgradeData) {
		SMMap clonedUpgradeData = (SMMap) upgradeData.clone();
		beforeSave(entityName, clonedUpgradeData);
		newDatas.add(clonedUpgradeData);
	}

	@Override
	public void updateData(String entityName, SMMap customerData,
			SMMap upgradeData) {
		oldDatas.add(customerData);
		SMMap clonedUpgradeData = (SMMap) upgradeData.clone();
		beforeSave(entityName, clonedUpgradeData);
		newDatas.add(clonedUpgradeData);
	}

	@Override
	public void updateDatas(String entityName, List<SMMap> customerDatas,
			List<SMMap> upgradeDatas) {
		for (SMMap customerData : customerDatas) {
			oldDatas.add(customerData);
		}
		for (SMMap upgradeData : upgradeDatas) {
			SMMap clonedUpgradeData = (SMMap) upgradeData.clone();
			beforeSave(entityName, clonedUpgradeData);
			newDatas.add(clonedUpgradeData);
		}
	}

	@Override
	public void addResult(String fileName, Object[] keyValues,
			UpgradeResult result) {
		SMMap upgradeResult = UpgradeUtil.createUpgradeResult(fileName,
				keyValues, result);
		upgradeResults.add(upgradeResult);
	}

	@Override
	public void flush(String entityName) {
		for (SMMap oldData : oldDatas) {
			template.delete(entityName, oldData);
		}
		oldDatas.clear();

		for (SMMap newData : newDatas) {
			template.save(entityName, newData);
		}
		newDatas.clear();

		for (SMMap upgradeResult : upgradeResults) {
			template.save(UpgradePhase.UPGRADE_RESULTS, upgradeResult);
		}
		upgradeResults.clear();
	}

}
